package com.ht.api.task;

import javax.sql.DataSource;

import com.ht.api.db.Db;
import com.ht.api.db.DbConfig;
import com.ht.api.db.DbList;
import com.ht.api.db.Entity;
import com.ht.api.db.StreamLoadConfig;
import com.ht.api.db.task.HtTaskExecutor;
import com.ht.api.db.task.TaskHandler;
import com.ht.api.service.AudienceService;

import cn.hutool.json.JSONObject;

/**
 * 人群定时任务
 * @author asq
 * @createTime 2025年3月19日 11:59:53
 */
public class AudienceTimerTask implements TaskHandler {

	@Override
	public String getName() {
		return "人群定时任务";
	}

	@Override
	public boolean handler(JSONObject requestParam, String groupId, long taskId) {
		DbList list = Db.createSqlParser("sys_tenant").query();
		list.stream().forEach(b -> {
			HtTaskExecutor.execute(() -> {
				Long tenantId = b.getLong("main_id");
				refreshAudience(tenantId);
			});
		});

		return true;
	}
	
	/**
	 * 执行某个具体租户的任务
	 * @param tenantId
	 */
	private void refreshAudience(long tenantId) {
        DataSource ds = DbConfig.useTenantDb(tenantId);
        StreamLoadConfig config = DbConfig.useTenantSLC(tenantId);

        DbList audienceList = Db.createSqlParser("audience").where("status", 1).where("init_status", 2).query(ds);
        for (Entity audience : audienceList) {
        	AudienceService.refreshAudience(ds, config, audience);
        }
	}

}
